package com.milhouz.bomberrokon.engines;

import android.content.Intent;

import com.milhouz.bomberrokon.BomberSlashActivity;
import com.milhouz.bomberrokon.engines.ai.AIPlayer;
import com.milhouz.bomberrokon.events.Event;
import com.milhouz.bomberrokon.events.EventManager;
import com.milhouz.bomberrokon.factories.MapFactory;
import com.milhouz.bomberrokon.model.GameRound;
import com.milhouz.bomberrokon.model.MapModel;

public class GameEngine extends Engine {

	/** Map model */
	public int nbPlayers;
	private MapModel mMapModel;

	/** Player AI */
	private AIPlayer mAiPlayer;

	/** Game round management */
	private GameRound mGameRound;
	// ---- Game data
	public static final int MAX_NB_BOMBS = 10;

	public GameEngine(BomberSlashActivity rokonActivity) {
		super(rokonActivity);
		final Intent callingIntent = mRokonActivity.getIntent();
		int nbOpponents = callingIntent.getIntExtra("opponents", 1);
		nbPlayers = nbOpponents + 1;
	}

	@Override
	public void createEngine() {
	}

	@Override
	public void loadEngine() {
		// Get game settings from previous activities or preferences
		final Intent callingIntent = mRokonActivity.getIntent();
		String mapCode = callingIntent.getStringExtra("mapCode");
		int time = callingIntent.getIntExtra("timer", 30);
		int nbRounds = callingIntent.getIntExtra("nbRounds", 3);
		int currentRound = callingIntent.getIntExtra("currentRound", 1);
		int[] victories = new int[nbPlayers];
		for (int i = 0; i < nbPlayers; i++) {
			victories[i] = callingIntent.getIntExtra("PLAYER" + i, 0);
		}

		// Create the map model
		mMapModel = MapFactory.getFactory().loadMapModel(mapCode);
		// Create AI Player
		mAiPlayer = new AIPlayer(mMapModel);
		// Create initialize game round
		mGameRound = new GameRound(time, nbPlayers, nbRounds, currentRound, victories);
	}

	@Override
	public void step() {
		// Game round step process
		if (mGameRound.isFinished() && !mGameRound.isEndRoundShowed()) {
			// Send end round event
			EventManager.pushEvent(new Event(Event.END_ROUND_EVENT));
		} else {
			// Update AI Playe
			for (int i = 1; i <= nbPlayers - 1; i++) {
				mAiPlayer.step(mGraphicEngine.getBomberBotSprites(i));
			}
		}
	}

	@Override
	public void processEvent(Event event) {
		mGameRound.processEvent(event);
	}

	public MapModel getMapModel() {
		return mMapModel;
	}

	public AIPlayer getAiPlayer() {
		return mAiPlayer;
	}

	public GameRound getGameRound() {
		return mGameRound;
	}

	public int getNbPlayers() {
		return nbPlayers;
	}

}
